﻿
function submitClick() {
    //debugger;
    //$('#demo').jstree('refresh', -1);
    table_name = $("#drp_hier option:selected").data("TableName");
    hier_id = $("#drp_hier").val();
    vers_id = $("#drp_ver").val();

    //validation 
    var bvalidmsg = validationOnSubmit(hier_id, vers_id);
    if (bvalidmsg != "") { alert(bvalidmsg); return false; }

    //BindTree(true);
    if ($("#demo").children().length === 0) {
        BindTree(true);
    }
    else {
        //debugger;
        $.get('Callback.aspx?reconstruct=1', function () {
            //debugger;
            $('#demo').children().remove().end();
            BindTree(true);
        });
    }

    ClearScreen();
    ////add dimension tabs dynamically
    getTabs();
    ////end of adding dimensions

}


$("#set_theme").click(function () {
    //////////////debugger;
    $("#demo").jstree("set_theme", "apple");
    $('#demo').jstree('refresh', -1);
});


//add node types in submenu on create click
$("#create").click(function () {
   // debugger;

    if ($("ul.sf-menu").children().length == 0) {
        $(this).css("background", "#eef4d3 url(../Images/left.png) center right no-repeat");
        var id = $('#demo').jstree('get_selected').attr('id');
        var typeid = $('#demo').jstree('get_selected').attr('typeid');
        var table_name = $("#drp_hier option:selected").data("TableName");
        var vers_id = $("#drp_ver").val();

        $.ajax({
            async: true,
            type: 'POST',
            url: "Callback.aspx?operation=create_child&id=" + id + "&type_id=" + typeid + "&hier_id=" + $("#drp_hier").val() + "&vers_id=" + vers_id + "&table_name=" + table_name + "&txtdate=" + $('#txt_date').val(),
            success: function (str) {
                //////debugger;
                var data = eval('(' + str + ')');
                $("ul.sf-menu").empty();
                $("#tmplListItems").tmpl(data).appendTo("ul.sf-menu");
                $("#divNodeList").css("display", "block");
                $("#divNodeList").css("visibility", "visible");
                // initialise plugins
                $("ul.sf-menu").show();
            }
        });
    }
    else {
        $("ul.sf-menu").empty();
        $(this).css("background", "#eef4d3 url(../Images/down.png) center right no-repeat");
    }
});


//on selection of radio button 
//'as of toady' disable date control
function disabledate() {
    //////debugger;
    var optval = $("input[name='sdate']:checked").val();
    var startDate = $('#drp_ver option:selected').attr("start_date");
    var endDate = $('#drp_ver option:selected').attr("end_date");

    if (optval == "todate") {
        $('#txt_date').attr('disabled', true);
        var todate = getCurrDate();
        $('#txt_date').val(todate);
        $("#txt_date").datepicker('disable');
    }
    else {

        $('#txt_date').attr('disabled', false);
        var prevdate = getDate(-1);
        $('#txt_date').val(prevdate);
        $('#txt_date').datepicker("enable");
        //set the range of that version
        $("#txt_date").datepicker('option', { minDate: new Date(startDate), maxDate: new Date(endDate) });
    }

    //on change clear tree and attribute block
    ClearScreen();

}


function BindCombo(opr, id, comboid, tab, addTblName) {
   // debugger;

    var page;
    if (tab == "hier") { page = "Callback.aspx"; }
    else if (tab == "master") { page = "MasterCallback.aspx"; }
    else if (tab == "reEng") { page = "ConfigCallback.aspx"; };

    $.ajax({
        async: false,
        type: 'POST',
        url: page + "?operation=" + opr + "&id=" + id + "&txtdate=" + $('#txt_date').val(),
        success: function (str) {
            var data = eval('(' + str + ')');

            //debugger;

            $("#" + comboid).empty();
            $("#tmplOptions").tmpl(data).appendTo("#" + comboid);
            //if (comboid === "drp_hier" || comboid === "drp_mst" || comboid === "drp_dimension") {
            if (addTblName === true) {
                $("#" + comboid + " option").each(function (i) {
                    $(this).data("TableName", data[i].TableName);
                });
            }

            if (comboid == 'drp_ver') {
                $("#" + comboid + " option").each(function (i) {
                   // debugger;
                    $(this).attr("start_date", data[i].start_date);
                    $(this).attr("end_date", data[i].end_date);
                });
            }
        }
    });
}


//save attributes
function saveAttributes() {

    // ////debugger;
    var bval = validateAttr();
    if (bval == false) { return false; };
    //var tree = jQuery.jstree._reference("#demo");
    hier_id = $("#drp_hier").val();
    vers_id = $("#drp_ver").val();
    var typeid = $('#demo').jstree('get_selected').attr('typeid');
    var node_id = $("#demo").jstree('get_selected').attr("id");

    var jsonstring = "["
    $(".attrText").each(function () {
        //////debugger;
        var colName = $(this).attr("colName");
        var colValue;
        if ($(this).attr("control_type") == 'dropdown') {
            colValue = $(this).find(":selected").val();
        }
        else { colValue = $(this).val(); }

        jsonstring = jsonstring + '{"colname" :  "' + colName + '", "colvalue" :  "' + colValue + '"},';
    });

    jsonstring = jsonstring.substring(0, jsonstring.length - 1) + "]";
    table_name = $("#drp_hier option:selected").data("TableName");

    $.ajax({
        async: true,
        type: 'POST',
        url: "Callback.aspx?operation=save_attributes&atrrVal=" + jsonstring + "&table_name=" + table_name + "&id=" + node_id + "&hier_id=" + hier_id + "&vers_id=" + vers_id + "&type_id=" + typeid,
        success: function (str) {
            if (str == "false") {
                alert("Error in save !");
                return false;
            }
            else {
                //$("#hdn_bAttrVal").attr('value', "1"); 
                alert("saved successfully !");
                return false;
            }
        }
    });

}


//validate mandatory fields of attributes
function validateAttr() {
    var bflag = true;

    $("[is_req='True']").each(function (index, elem) {
        //numberOnly(elem);
        if (elem.value == "") {
            alert("please enter " + $(elem).attr('colname'));
            bflag = false;
            return bflag;
        }
    });

    return bflag;
}

//validation on submit for date and hier and ver selection
function validationOnSubmit(hier_id, ver_id) {
    //////debugger;
    var msg = "";
    if ($.trim(hier_id) == "") { msg = "Please select hierarchy"; return msg; }
    if ($.trim(ver_id) == "") { msg = "Please select version"; return msg; }

    //min date validation if historical date 
    // (it should not be less than that hier_id and ver_id start date)
    var optval = $("input[name='sdate']:checked").val();

    if (optval == "histdate") {
        $.ajax({
            async: true,
            type: 'POST',
            url: "Callback.aspx?operation=check_date" + "&hier_id=" + hier_id + "&vers_id=" + ver_id + "&txtdate=" + $('#txt_date').val(),
            success: function (str) {
                if (str == "false") { msg = "this date doesnot belong to selected version"; return msg; }
            }
        });
    }

    return msg;
}


// Code for the menu buttons
$(function () {
    $("#mmenu input").click(function () {
        switch (this.id) {
            case "add_default":
            case "add_folder":
                $("#demo").jstree("create", null, "last", { "attr": { "rel": this.id.toString().replace("a d_", "")} });
                break;
            case "search":
                $("#demo").jstree("search", document.getElementById("text").value);
                break;
            case "text": break;
            default:
                $("#demo").jstree(this.id);
                break;
        }
    });
});


function ClearScreen() {

    //$('#demo').empty();

    // to hide the attribute block on toggle 
    //$("#tbl_Buttons").css("display", "none");

    $("#tbl_Buttons").hide();

    // $("#NodeAttr").css("display", "none");
    $("#NodeAttr").hide();

}

//clears the atrribute table elements
function ClearAttributes() {
    // ////debugger;
    $(".attrText").filter('select,input,textarea').val('');
    $(".attrText").filter('checkbox,radio').checked('false');
}

function loadGriddataDim(dimname, node_id, index, opt) {

    ////debugger;
    var table_name = $("#drp_hier option:selected").data("TableName");
    hier_id = $("#drp_hier").val();
    vers_id = $("#drp_ver").val();
    var opr;
    //  var node_id = $("#demo").jstree('get_selected').attr("id");

    //////debugger;
    //    if ($("#demo").jstree('get_selected')) {
    //        if ($("#demo").jstree('get_selected').attr("isleaf") == "1") {
    //            $('input[id=btn' + dimname + '_arel]').show();
    //            $('input[id=btn' + dimname + '_rrel]').show();
    //        }
    //        else {
    //            $('input[id=btn' + dimname + '_arel]').hide();
    //            $('input[id=btn' + dimname + '_rrel]').hide();
    //        }
    //    }

    if (node_id != 0 && node_id != undefined) {

        if (opt == "exist") {
            //jqgrid table name
            var tblnameEx = "#dtgrid" + dimname + "ex";
            //pager div
            var pgnameEx = "#pg" + dimname + "ex";
            opr = "get_griddata";
            //node_id = $("#demo").jstree('get_selected').attr("id");
            //alert(node_id);
            var url = "Callback.aspx?operation=" + opr + "&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&txtdate=" + $('#txt_date').val();
            //opr = "get_gridColdata"; //get_gridColdata
        }

        //not needed now
        //    else {
        //        //jqgrid table name
        //        var tblnameUn = "#dtgrid" + dimname + "un";
        //        //pager div
        //        var pgnameUn = "#pg" + dimname + "un";
        //        opr = "get_griddataUn";
        //    }

        $.ajax({
            async: true,
            type: 'GET',
            url: "Callback.aspx?operation=get_gridColdata&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&txtdate=" + $('#txt_date').val(),
            data: "",
            dataType: "json",
            success: function (griddata) {
                // //debugger;
                if (opt == "exist") {
                    var result = griddata.gridEx;
                    if (node_id != 0 && node_id != undefined) {
                        //to fill exist data grid
                        if (tempNodeId[index] == 0 || tempNodeId[index] == undefined) {
                            ////debugger;
                            fillgrid(griddata.gridEx, tblnameEx, pgnameEx, "550px", "200px", url,true);
                            jQuery(tblnameEx).jqGrid('navGrid', pgnameEx, { edit: false, add: false, del: false, search: true });

                        }
                        else {
                            ////debugger;
                            refreshgrid(griddata.gridEx, tblnameEx, url);
                        }

                        //to fill rules
                        //if (tempNodeId[index] == 0 || tempNodeId[index] == undefined) {
                        fillRules(griddata.gridEx, "dtgrid" + dimname + "_rule", griddata.rules, "hdn" + dimname + "_obj", dimname); //dtgrid${dimabbr}_rule //"hdn${dimabbr}_obj"
                        //}
                        //else {
                        //refreshrule(griddata.gridEx, tblnameEx);
                        //}

                    }
                }

                //not needed now
                //            else {

                //                //////debugger;
                //                ///to fill un-assigned data grid
                //                if (tempNodeId[index] == 0 || tempNodeId[index] == undefined) {
                //                    fillgrid(griddata.gridUnassign, tblnameUn, pgnameUn, "200px", "200px");
                //                }
                //                else {
                //                    refreshgrid(griddata.gridUnassign, tblnameUn);
                //                }
                //            }

                tempNodeId[index] = node_id;
            },
            error: function (x, e) {
                // ////debugger;
                alert(x.readyState + " " + x.status + " " + e.msg);
            }
        });

    }
}


//to fill jqgird -common function
//function fillgrid(result, tblname, pgname, gWidth, gHeight, dimname, url) {
function fillgrid(result, tblname, pgname, gWidth, gHeight, url,multiselect) {
    //debugger;

    // var colD = result.datarow, colN = result.columns, colM = result.colModelList;
    //var opr = "get_griddata"; 
    var colN = result.columns, colM = result.colModelList;

    jQuery(tblname).jqGrid({
        // data: colD,
        // datatype: 'local',
        //url: "Callback.aspx?operation=" + opr + "&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&txtdate=" + $('#txt_date').val(),
        url: url,
        datatype: 'json',
        gridview: true,
        colNames: colN,
        colModel: colM,
        caption: "Master Data",
        //url: "Callback.aspx?operation=get_Dimrows&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id,
        // editurl: "MasterCallback.aspx?table_name=" + table_name + "&list_id=" + list_id,
        rowNum: 15,
        //pager: '#pager',
        pager: pgname,
        sortname: result.primarykey,
        sortorder: "desc",
        //        width: "200px",
        //        height: "200px",
        width: gWidth,
        height: gHeight,
        scrollOffset: 18,
        closeAfterEdit: true,
        ignoreCase: true,
        multiselect: multiselect, //true,
        viewrecords: true,
        loadComplete: function (data) {
            jQuery(tblname).hideCol(result.primarykey);
            if (gWidth == "200px" || gWidth == "550px") {
                jQuery(tblname).setGridWidth("550", true);
            }            
            else {
                jQuery(tblname).setGridWidth("800", true);
            }
        },
        loadError: function (xhr, status, error) {
            alert('error');
        }
    });

}

function refreshgrid(result, tblname, url) {
    ////debugger;
    //var colD = result.datarow, colN = result.columns, colM = result.colModelList;
    //clear grid data
    $(tblname).jqGrid("clearGridData", true);

    if (url == null || url == undefined) {
        //refresh jqgrid
    jQuery(tblname).jqGrid('setGridParam',
    {
        //datatype: 'local',
        //data: colD 
        //url: url,
        datatype: 'json'
    }).trigger("reloadGrid");

    }
    else {

        //refresh jqgrid
    jQuery(tblname).jqGrid('setGridParam',
    {
        //datatype: 'local',
        //data: colD 
        url: url,
        datatype: 'json'
    }).trigger("reloadGrid");

    }
}

//naval for hidden search tool

//to fill rules grid and rules
function fillRules(result, dtgridRule, rules, hiddenfield, dimname) {
   // debugger;
    $('input[name=' + hiddenfield + ']').val(rules.currentObj);

    // $("#div_" + dimname + "parent")[0].innerHTML = rules.ancesrtosRule;
    if (rules.ancesrtosRule == null || rules.ancesrtosRule == "") {
        $("#div_" + dimname + "parent")[0].innerHTML = "";
    }
    else {
        $("#div_" + dimname + "parent")[0].innerHTML = rules.ancesrtosRule;
    }


    //    if (rules.currentRule != null) {
    //        $("#div_" + dimname + "currule")[0].innerHTML = rules.currentRule;
    //    }
    //    else {
    //        $("#div_" + dimname + "currule")[0].innerHTML = "";
    //    }


    if (rules.currentRule == "" || rules.currentRule == null) {
        $('input[id=btn' + dimname + '_rule]').val("Add Rule");   //"btn${dimabbr}_rule"
        $("#div_" + dimname + "currule")[0].innerHTML = "";
    }
    else {
        $('input[id=btn' + dimname + '_rule]').val("Edit Rule");   //"btn${dimabbr}_rule"
        $("#div_" + dimname + "currule")[0].innerHTML = rules.currentRule;
    }

    var colN = result.columns, colM = result.colModelList;
    $("#" + dtgridRule).GridUnload();

    jQuery("#" + dtgridRule).jqGrid({
        datatype: 'local',
        colNames: colN,
        colModel: colM,
        width: "10px",
        ignoreCase: true,
        loadComplete: function (data) {
            jQuery("#" + dtgridRule).hideCol(result.primarykey);
            jQuery("#" + dtgridRule).setGridWidth(400, true);
            $("#gview_" + dtgridRule).hide(); //pg_pager
            //$("#pager").hide();
            $('#gbox_' + dtgridRule).removeClass('ui-widget-content');

        },
        loadError: function (xhr, status, error) {
            //////debugger;
            alert('error');
        }
    });
}


//set rules
function set_rule(abbr, tblname) {
   // debugger;
    var node_id = $("#demo").jstree('get_selected').attr("id");

    if (node_id == undefined) {
        alert("Please select node to add rule !");
        return false;
    }
    else {

        dimension = abbr;
        var pSearch =
                {
                    drag: true,
                    multipleSearch: true,
                    multipleGroup: true,
                    showQuery: true,
                    showRel: true,
                    overlay: false,
                    resetFilterAllRows: true,
                    modal: true
                };


        var template = $('input[name=hdn' + abbr + '_obj]').val();
        $("#" + tblname).jqGrid("searchGrid", pSearch);


        var obj = $('input[name=hdn' + abbr + '_obj]').val();   // "hdn" + dimname + "_obj"
        //, defaultFilters);
        // debugger;

        $("#fbox_" + tblname + "_search").hide(); //"fbox_dataGrid_search" //"fbox_dtgridACCT_rule_query""dtgrid${dimabbr}_rule"

        //hide show query button
        $("#fbox_" + tblname + "_query").hide();


        $("#fbox_" + tblname + "_search").css("left", "10px");
        $(".ui-jqdialog-title")[0].innerHTML = "Query..."; //"ui-jqdialog-title"
        $("#searchmodfbox_" + tblname).removeAttr("role");
        //////debugger;
        if (template == "" || template == null) {
            $("#fbox_" + tblname).jqFilter('addFilter', defaultFilters);
        } else {
            $("#fbox_" + tblname).jqFilter('addFilter', eval("'" + template + "'"));
        }  //"hdn" + dimname + "_obj"



        //    //////debugger;
        //    //get filter object
        //    var fl = $("#" + "fbox_" + tblname),
        //                sdata = {}, res,
        //                filters = fl.jqFilter('filterData');
        //    ///////
        //    //toSQLString
        //    var query = fl.jqFilter('toSQLString');
    }

}



//remove the relation of existing data
function remove_rel(dimname, tblgrid) {
    ////debugger;

    var Ids = jQuery(tblgrid).getGridParam('selarrrow');
    var node_id = $("#demo").jstree('get_selected').attr("id");
    var table_name = $("#drp_hier option:selected").data("TableName");
    hier_id = $("#drp_hier").val();

    if (Ids != undefined) {
        if (Ids.length != 0 && node_id != undefined) {

            var tblnameEx = "#dtgrid" + dimname + "ex";
            //refreshgrid(griddata.gridEx, tblnameEx);
            var url = "Callback.aspx?operation=remove_rel&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&Ids=" + Ids + "&txtdate=" + $('#txt_date').val();
            refreshgrid("data", tblnameEx, url);

            //            $.ajax({
            //                async: true,
            //                type: 'POST',
            //                //url: "Callback.aspx?operation=remove_rel&hier_id=" + $("#drp_hier").val(),
            //                url: "Callback.aspx?operation=remove_rel&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&Ids=" + Ids + "&txtdate=" + $('#txt_date').val(),
            //                success: function (data) { //griddata
            //                   // //debugger;
            //                    //var griddata = eval('(' + data + ')');
            //                   // var url = "Callback.aspx?operation=" + opr + "&table_name=" + table_name + "&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&txtdate=" + $('#txt_date').val();
            //                    var url = "";

            //                    // refresh exist grid
            //                    var tblnameEx = "#dtgrid" + dimname + "ex";
            //                    //refreshgrid(griddata.gridEx, tblnameEx);                 
            //                    refreshgrid(data, tblnameEx, url);

            //                    //data
            //                    //refresh un-assigned grid - not needed now
            //                    //var tblnameUn = "#dtgrid" + dimname + "un";
            //                    //refreshgrid(griddata.gridUnassign, tblnameUn);
            //                }
            //            });


        }
        else {
            alert("Please select dimension to remove relation");
            return false;
        }
    }
    else {
        alert("Please select dimension to remove relation");
        return false;
    }

}

//add the relation of un-assigned dimension
function add_rel(dimname, tblgrid) {

    // //debugger;
    var Ids = jQuery(tblgrid).getGridParam('selarrrow');
    var node_id = $("#demo").jstree('get_selected').attr("id");
    var table_name = $("#drp_hier option:selected").data("TableName");
    hier_id = $("#drp_hier").val();

    if (Ids != undefined) {
        if (Ids.length != 0 && node_id != undefined) {
            $.ajax({
                async: true,
                type: 'POST',
                url: "Callback.aspx?operation=add_relUnassign&dimname=" + dimname + "&hier_id=" + hier_id + "&node_id=" + node_id + "&Ids=" + Ids + "&vers_id=" + $("#drp_ver").val() + "&txtdate=" + $('#txt_date').val(),
                success: function (data) {
                    // ////debugger;
                    // var griddata = eval('(' + data + ')');

                    //refresh un-assigned grid - not needed now
                    // var tblnameUn = "#dtgrid" + dimname + "un";
                    // refreshgrid(griddata.gridUnassign, tblnameUn);

                    // refresh exist grid
                    var tblnameEx = "#dtgrid" + dimname + "ex";
                    //refreshgrid(griddata.gridEx, tblnameEx);
                    refreshgrid(data, tblnameEx, "url");

                }
            });
        }
        else {
            alertmsgAddRel(Ids, node_id);
        }
    }
    else {
        alertmsgAddRel(Ids, node_id);
    }

}

//alert message of add relation
function alertmsgAddRel(Ids, node_id) {

    if (Ids.length === 0 || Ids == undefined) {
        alert("Please select dimension to add relation");
        return false;
    }
    else if (node_id == undefined) {
        alert("Please select node to add relation");
        return false;
    }
}


//on click of add relation 
function showAddRelation(dimname, tblgrid) {

    //debugger;

    var node_id = $("#demo").jstree('get_selected').attr("id");
    if (node_id != undefined) {

        var table_name = $("#drp_hier option:selected").data("TableName");
        var hier_id = $("#drp_hier").val();
        //dialogTop=50px;
        //var left = (screen.width / 2) - (w / 2);
        //var top = (screen.height / 2) - (h / 2);
        var left = (screen.width / 2) - (900 / 2);
        var top = ((screen.height / 2) - (520 / 2)-30) ;
        //alert(left + " " + top);

        var DialogOptions = "Scrollbar=No; dialogWidth=900px; dialogHeight=520px;dialogTop=" + top.toString() + "px;dialogLeft=" + left.toString() + "px;Help=No;Status=No;Resizable=Yes;";

        var OpenUrl = "AddRelation.aspx?node_id=" + node_id + "&hier_id=" + hier_id + "&table_name=" + table_name + "&vers_id=" + $("#drp_ver").val() + "&dimname=" + dimname + "&txtdate=" + $('#txt_date').val();
        var ret = window.showModalDialog(OpenUrl, "Yes", DialogOptions);

        //debugger;

        //if added the relation refresh grid of both exist and un-assigned
        //if (typeof (ret) != "true") {
        if (ret == "true") {
            var url = "Callback.aspx?operation=refresh_grid&dimname=" + dimname + "&hier_id=" + hier_id + "&table_name=" + table_name + "&node_id=" + node_id + "&vers_id=" + $("#drp_ver").val() + "&txtdate=" + $('#txt_date').val();
            var tblnameEx = "#dtgrid" + dimname + "ex";
            refreshgrid("data", tblnameEx, url);

            //            $.ajax({
            //                async: true,
            //                type: 'POST',
            //                url: "Callback.aspx?operation=refresh_grid&dimname=" + dimname + "&hier_id=" + hier_id + "&table_name=" + table_name + "&node_id=" + node_id + "&vers_id=" + $("#drp_ver").val() + "&txtdate=" + $('#txt_date').val(),
            //                success: function (data) {
            //                    ////debugger;
            //                    var griddata = eval('(' + data + ')');

            //                    //refresh un-assigned grid - not needed now
            //                    //var tblnameUn = "#dtgrid" + dimname + "un";
            //                    //refreshgrid(griddata.gridUnassign, tblnameUn);

            //                    // refresh exist grid
            //                    var tblnameEx = "#dtgrid" + dimname + "ex";
            //                    //refreshgrid(griddata.gridEx, tblnameEx);
            //                    refreshgrid(data, tblnameEx,"url");


            //                }
            //            });
        }
    }
    else {
        //alertmsgAddRel(Ids, node_id);
        alert("Please select node to add relation");
        return false;
    }
}



//on click of refresh relation 
function showRefreshRel(queryRel, queryObj) {

    //debugger;

    var node_id = $("#demo").jstree('get_selected').attr("id");
    if (node_id != undefined) {

        var table_name = $("#drp_hier option:selected").data("TableName");
        var hier_id = $("#drp_hier").val();

        //save rule   
        var bRule;
        if ($('input[id=btn' + dimension + '_rule]').val() == "Add Rule") {
            bCurrRule = false;
        }
        else {
            bCurrRule =true;
        }

        if (queryObj) {
            try {
                // xmlJsonClass or JSON.stringify
                res = xmlJsonClass.toJson(queryObj, '', '', false);
            } catch (e) {
                try {
                    res = JSON.stringify(queryObj);
                } catch (e2) { }
            }
        }

        ////debugger;
        //compare querObj before save
        //var template = $('input[name=hdn' + abbr + '_obj]').val();
        var Obj = $('input[name=hdn' + dimension + '_obj]').val();
        Obj = Obj.replace(/\\/g, "");

        var url = "SetRelation.aspx?node_id=" + node_id + "&hier_id=" + hier_id + "&table_name=" + table_name + "&vers_id=" + $("#drp_ver").val() + "&dimname=" + dimension + "&txtdate=" + $('#txt_date').val() + "&queryRel=" + queryRel;

        if ('"' + JSON.stringify(queryObj) + '"' == JSON.stringify(Obj).replace(/\\/g, "")) {
            OpenRefreshDialog(queryRel, queryObj, url);
        }
        else {

            $.ajax({
                async: true,
                type: 'POST',
                url: "Callback.aspx?operation=saveRule&node_id=" + node_id + "&dimname=" + dimension + "&hier_id=" + hier_id + "&vers_id=" + $("#drp_ver").val() + "&queryRel=" + queryRel + "&queryObj=" + res + "&bCurrRule=" + bCurrRule + "&table_name=" + table_name + "&txtdate=" + $('#txt_date').val(),
                success: function (str) { //griddata
                    ////debugger;
                    if (str == "false") {
                        alert("Error in Save !");
                        return false;
                    }
                    else {

                        OpenRefreshDialog(queryRel, queryObj, url);

                        //                        //update query in rule tab
                        //                        //"div_${dimabbr}currule"
                        //                        ////debugger;
                        //                        $("#div_" + dimension + "currule")[0].innerHTML = queryRel;

                        //                        //open refresh relation dialog 
                        //                        var DialogOptions = "Center=Yes; Scrollbar=No; dialogWidth=930px; dialogTop=250px; dialogHeight=680px; Help=No; Status=No; Resizable=No;";
                        //                        var OpenUrl = "SetRelation.aspx?node_id=" + node_id + "&hier_id=" + hier_id + "&table_name=" + table_name + "&vers_id=" + $("#drp_ver").val() + "&dimname=" + dimension + "&txtdate=" + $('#txt_date').val() // + "&queryRel=" + queryRel
                        //                        var ret = window.showModalDialog(OpenUrl, "Yes", DialogOptions);
                        //                        ////debugger;
                        //                        //close search dialog            
                        //                        $("a.ui-jqdialog-titlebar-close").click();

                        //                        //if added the relation refresh grid of both exist and un-assigned
                        //                        if (typeof (ret) != "true") {
                        //                            $.ajax({
                        //                                async: true,
                        //                                type: 'POST',
                        //                                url: "Callback.aspx?operation=refresh_grid&dimname=" + dimension + "&hier_id=" + hier_id + "&node_id=" + node_id + "&vers_id=" + $("#drp_ver").val() + "&txtdate=" + $('#txt_date').val() + "&table_name=" + table_name,
                        //                                success: function (data) {
                        //                                    ////debugger;
                        //                                    var griddata = eval('(' + data + ')');
                        //                                    var tblnameEx = "#dtgrid" + dimension + "ex";
                        //                                    refreshgrid(griddata.gridEx, tblnameEx);
                        //                                }
                        //                            });
                        //                        }

                    }

                }
            });
        }

    }
    else {
        //alertmsgAddRel(Ids, node_id);
        alert("Please select node to add relation");
        return false;
    }
}

function OpenRefreshDialog(queryRel, queryObj, OpenUrl) {


    //update query in rule tab
    //"div_${dimabbr}currule"
    // //debugger;
    $("#div_" + dimension + "currule")[0].innerHTML = queryRel;
    $('input[name=hdn' + dimension + '_obj]').val(queryObj);
    var node_id = $("#demo").jstree('get_selected').attr("id");

    var left = (screen.width / 2) - (930 / 2);
    var top = ((screen.height / 2) - (580 / 2) - 30);

    //open refresh relation dialog 
    var DialogOptions = "Center=Yes; Scrollbar=No; dialogWidth=930px; dialogHeight=580px; Help=No; Status=No; Resizable=No;DialogTop="+ top + "px;DialogLeft=" + left + "px;";
    // var OpenUrl = "SetRelation.aspx?node_id=" + node_id + "&hier_id=" + hier_id + "&table_name=" + table_name + "&vers_id=" + $("#drp_ver").val() + "&dimname=" + dimension + "&txtdate=" + $('#txt_date').val() // + "&queryRel=" + queryRel
    // var   

    var ret = window.showModalDialog(OpenUrl, "Yes", DialogOptions);          
   

    //debugger;
    //alert(ret);

    //if added the relation refresh grid of both exist and un-assigned
    // if (typeof (ret) != "true") {
    if (ret == "true") {

        //original before url of jqgrid
        //        $.ajax({
        //            async: true,
        //            type: 'POST',
        //            url: "Callback.aspx?operation=refresh_grid&dimname=" + dimension + "&hier_id=" + hier_id + "&node_id=" + node_id + "&vers_id=" + $("#drp_ver").val() + "&txtdate=" + $('#txt_date').val() + "&table_name=" + table_name,
        //            success: function (data) {
        //                ////debugger;
        //                var griddata = eval('(' + data + ')');
        //                var tblnameEx = "#dtgrid" + dimension + "ex";
        //                refreshgrid(griddata.gridEx, tblnameEx,"url");
        //            }
        //        });

        //refresh exist grid
        var url = "Callback.aspx?operation=refresh_grid&dimname=" + dimension + "&hier_id=" + hier_id + "&node_id=" + node_id + "&vers_id=" + $("#drp_ver").val() + "&txtdate=" + $('#txt_date').val() + "&table_name=" + table_name;
        var tblnameEx = "#dtgrid" + dimension + "ex";
        refreshgrid("griddata.gridEx", tblnameEx, url);

    }

    //debugger;
    //close search dialog   
    $("a.ui-jqdialog-titlebar-close").click();

}


function DisableTab(res) {

    //debugger;
    var data = eval('(' + res + ')');
    var arr = [];
    var arrEnab = [];

    if (data["IS_DASHBOARD_ALLOWED"] == false) { arr.push(0); }
    else { arrEnab.push(0); }

    if (data["IS_DIMESIONS_ALLOWED"] == false) { arr.push(1); }
    else { arrEnab.push(1); }

    if (data["IS_GROUPING_ALLOWED"] == false) { arr.push(2); }
    else { arrEnab.push(2); }

    if (data["IS_REPORT_ALLOWED"] == false) { arr.push(3); }
    else { arrEnab.push(3); }

    if (data["IS_CONFIG_ALLOWED"] == false) { arr.push(4); }
    else { arrEnab.push(4); }

    //original
//    if (data["IS_DASHBOARD_ALLOWED"] == "false") { arr.push(0); }
//    else { arrEnab.push(0); }

//    if (data["IS_DIMESIONS_ALLOWED"] == "false") { arr.push(1); }
//    else { arrEnab.push(1); }

//    if (data["IS_GROUPING_ALLOWED"] == "false") { arr.push(2); }
//    else { arrEnab.push(2); }

//    if (data["IS_REPORT_ALLOWED"] == "false") { arr.push(3); }
//    else { arrEnab.push(3); }

//    if (data["IS_CONFIG_ALLOWED"] == "false") { arr.push(4); } 
//    else { arrEnab.push(4); }

    //select tab
    if (arrEnab[0] != 0) {
        $('#tabs').tabs('select', arrEnab[0]);
    }
    //disable tabs
    $("#tabs").tabs({ disabled: arr });

}


